package com.tanhua.dubbo.api;

import cn.hutool.core.convert.Convert;
import com.mongodb.client.result.UpdateResult;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.Video;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@DubboService
public class CommentsApiImpl implements CommentsApi {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private MovementApi movementApi;

    /**
     * 保存更新互动数据
     *
     * @param comment
     * @return
     */
    @Override
    public Integer saveComments(Comment comment) {
        //查询动态详情
        Movement movement = mongoTemplate.findById(comment.getPublishId(), Movement.class);
//        assert movement != null:"无该动态信息！";
        //封装评论对象发布动态用户Id
        if (movement != null) {
            comment.setPublishUserId(movement.getUserId());
        }
        mongoTemplate.save(comment);

        //更新动态表数据
        Query query = new Query(Criteria.where("id").is(comment.getPublishId()));
        Update update = new Update();

        if (comment.getCommentType() == CommentType.COMMENT.getType()) {
            //评论
            update.inc("commentCount", 1);
        } else if (comment.getCommentType() == CommentType.LIKE.getType()) {
            update.inc("likeCount", 1);
        } else if (comment.getCommentType() == CommentType.VIDEOCOMMENT.getType()) {
            update.inc("commentCount", 1);
        } else {
            update.inc("loveCount", 1);
        }

        //更新并且修改
        Movement modify = mongoTemplate.findAndModify(query, update, Movement.class);
        if (modify != null) {
            //5、获取最新的评论数量，并返回
            return modify.statisCount(comment.getCommentType());
        } else {
            Video video = mongoTemplate.findAndModify(query, update, Video.class);
            return video.statisCount(comment.getCommentType());
        }


    }

    /**
     * 查询互动评论列表
     *
     * @param movementId
     * @param comment
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public List<Comment> findComments(String movementId, CommentType comment, Integer page, Integer pagesize) {
        Query query = new Query();
        query.addCriteria(Criteria
                .where("publishId").is(new ObjectId(movementId))
                .and("commentType").is(comment.getType()))
                .with(Sort.by(Sort.Direction.DESC, "created"))
                .with(PageRequest.of((page - 1), pagesize))
        ;
        List<Comment> comments = mongoTemplate.find(query, Comment.class);
        return comments;
    }

    /**
     * 判断互动信息是否存在
     *
     * @param movementId
     * @param userId
     * @param like
     * @return
     */
    @Override
    public Boolean hasComment(String movementId, Long userId, CommentType like) {
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId)
                .and("publishId").is(new ObjectId(movementId))
                .and("commentType").is(like.getType()));
        return mongoTemplate.exists(query, Comment.class);
    }

    @Override
    public Integer delete(Comment comment) {
        //1、删除Comment表数据
        Criteria criteria = Criteria.where("userId").is(comment.getUserId())
                .and("publishId").is(comment.getPublishId())
                .and("commentType").is(comment.getCommentType());
        Query query = Query.query(criteria);
        mongoTemplate.remove(query, Comment.class);

        //更新动态表数据
        Query query1 = new Query(Criteria.where("id").is(comment.getPublishId()));
        Update update = new Update();

        if (comment.getCommentType() == CommentType.COMMENT.getType()) {
            //评论
            update.inc("commentCount", -1);
        } else if (comment.getCommentType() == CommentType.LIKE.getType()) {
            update.inc("likeCount", -1);
        } else {
            update.inc("loveCount", -1);
        }
        Movement modify = mongoTemplate.findAndModify(query1, update, Movement.class);
        Integer statisCount = modify.statisCount(comment.getCommentType());

        return statisCount;
    }

    @Override
    public Integer updateCommentsLike(String commentsId, Integer s) {
        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(new ObjectId(commentsId)));
        Update update = new Update();
        update.inc("likeCount", s);
        UpdateResult updateResult = mongoTemplate.updateFirst(query, update, Comment.class);
        long count = updateResult.getModifiedCount();
        return Convert.convert(Integer.class, count);
    }
}
